﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;

namespace COC.Commons
{
    public class GameConfig
    {
        private readonly XmlDocument _ConfigXml = new XmlDocument();

        public GameConfig()
        {
            _ConfigXml.Load(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "GameConfig.xml"));
        }

        public bool HasChildNodes(string xpath)
        {
            var element = _ConfigXml.DocumentElement?.SelectSingleNode(xpath);
            if (element != null)
                return element.HasChildNodes;
            return false;
        }

        /// <summary>
        ///     根据指定的XPath找到XML节点，将该节点下的所有节点按节点名为Key,属性text的值为value进行解析，返回该KeyValue的字典
        /// </summary>
        /// <param name="xpath">指定的XPath</param>
        public Dictionary<string, string> GetNodePropertiesMap(string xpath)
        {
            var map = new Dictionary<string, string>();
            var srcElement = _ConfigXml.DocumentElement?.SelectSingleNode(xpath);
            if (srcElement != null)
            {
                foreach (XmlElement ele in srcElement.ChildNodes)
                {
                    var name = ele.Name;
                    var text = ele.GetAttribute("text");
                    map.Add(name, text);
                }
            }
            return map;
        }
    }
}